package org.nanhill.support.hsqldb;

import org.hsqldb.Server;

import org.hsqldb.persist.HsqlProperties;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

import java.util.Properties;

/**
 * 在spring中以server模式启动hsqldb。
 * 
 * <pre>
 * &lt;bean id=&quot;hsqldb&quot; class=&quot;com.alibaba.sample.petstore.dal.util.HsqldbServerBean&quot;&gt;
 * &lt;property name=&quot;params&quot;&gt;
 * 		&lt;readProperties&gt;
 * 		&lt;prop key=&quot;server.database.0&quot;&gt;mem:.&lt;/prop&gt;
 * 		&lt;prop key=&quot;server.dbname.0&quot;&gt;petstore&lt;/prop&gt;
 * 		&lt;prop key=&quot;server.port&quot;&gt;9001&lt;/prop&gt;
 * 	&lt;/readProperties&gt;
 * &lt;/property&gt;
 * &lt;/bean&gt;
 * </pre>
 */
public class HsqldbServerBean implements InitializingBean, DisposableBean {
	private Properties params;

	private Server server;

	public void setParams(Properties params) {
		this.params = params;
	}

	public void afterPropertiesSet() throws Exception {
		if ((params == null) || params.isEmpty()) {
			throw new IllegalArgumentException("missing hsqldb params");
		}

		server = new Server();

		HsqlProperties props = new HsqlProperties(params);

		server.setProperties(props);

		server.setLogWriter(null);
		server.setErrWriter(null);

		server.start();
	}

	public void destroy() throws Exception {
		if (server != null) {
			server.stop();
		}
	}
}
